package com.winit.commons.filter;

import com.winit.commons.util.LoginUser;
import com.winit.commons.util.NetworkUtil;
import com.winit.commons.util.UserInfoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class SessionValidFilter implements Filter {

    private Logger log = LoggerFactory.getLogger(SessionValidFilter.class);

    private static final ThreadLocal<Date> timeCount = new ThreadLocal<Date>();

    public void destroy() {

    }

    private String beetle_auth_url;
    private String validate_flag;

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        // 做权限控制
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        String url = request.getRequestURI();// 用户请求地址
        String ip = NetworkUtil.getIpAddress(request);
        log.info("com.winit.commons.filter.SessionValidFilter#doFilter,url=" + url + ",ip=" + ip);

        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        Map queryMap = new HashMap();
        try {
            Enumeration enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                String paraName = (String) enu.nextElement();
                queryMap.put(paraName, request.getParameter(paraName));
            }
        } catch (Exception e) {
        }

        if (!StringUtils.isEmpty(validate_flag) && "true".equals(validate_flag)) {
            String tokenId = request.getParameter("tokenId");
            LoginUser user = UserInfoUtil.getUserInfo(tokenId, beetle_auth_url);
            if (user == null) {
                log.info("com.winit.commons.filter.SessionValidFilter#doFilter url=" + url + ".查询用户用户不存在.tokenId=" + tokenId);
                returnStatus(response, 403);
                return;
            }
        }

        Date startDate = new Date();
        timeCount.set(startDate);
        log.info("com.winit.commons.filter.SessionValidFilter#doFilter, start time " + startDate + ", url=" + url + "." + queryMap);
        chain.doFilter(req, res);
        Date endDate = new Date();
        log.info("com.winit.commons.filter.SessionValidFilter#doFilter, end time " + endDate + ", lastTime " + (endDate.getTime() - timeCount.get().getTime()) +", url=" + url + "." + queryMap);
    }


    public void init(FilterConfig config) throws ServletException {
        // TODO Auto-generated method stub
        this.beetle_auth_url = config.getInitParameter("beetle_auth_url");
        this.validate_flag = config.getInitParameter("validate_flag");
    }

    private void returnStatus(HttpServletResponse response, Integer status)
            throws IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
        response.setStatus(status);
    }
    
}
